﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Codeplex.Data.Internal
{
    internal class KeyIndexed<TKey, TElement> : IEnumerable<TElement>
    {
        public static KeyIndexed<TKey, TElement> Create<TSource>(
            IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector)
        {
            return new KeyIndexed<TKey, TElement>(source.ToDictionary(x => keySelector(x), x => elementSelector(x)));
        }

        readonly Dictionary<TKey, TElement> source;

        KeyIndexed(Dictionary<TKey, TElement> source)
        {
            this.source = source;
        }

        public TElement this[TKey key]
        {
            get
            {
                TElement value;
                return source.TryGetValue(key, out value)
                    ? value
                    : default(TElement);
            }
        }

        public IEnumerator<TElement> GetEnumerator()
        {
            return source.Values.GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}